# -*- coding: utf-8 -*-
import os
from datetime import datetime

from flask import Flask, session, request
from app import app

from properties import getProperty
from user.web import *
from friend.web import *
from comments.web import *
from location.web import *
from stream.web import *

@app.route('/')
@app.route('/123/')
def test():
    return 'welcome to showxun.com !'

############### upload file
from PIL import Image
IMAGE_RANG = (600, 1024)
THUMBNAIL_RANG1 = (150, 150)
THUMBNAIL_RANG2 = (100, 100)

ALLOWED_EXTENSIONS = set(['gif', 'png', 'jpg', 'jpeg', 'bmp'])
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/upload/f/', methods=['POST'])
def pic_upload():
    ''' images/{uid}/{pic} '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限，请登录')
    userImagePath = os.path.join(getProperty('upload_folder'), uid)
    if not os.path.exists(userImagePath):
        os.mkdir(userImagePath)
    imgFile = request.files['imgFile']
    if imgFile == None or not allowed_file(imgFile.filename):
        return error('610', u'文件格式不合法')

    ## 原图
    ctime = datetime.now()
    newImageFile = ctime.strftime("%y%m%d_%H%M%S_") + ctime.microsecond
    ext = imgFile.filename.rsplit('.', 1)[1]
    imgFile.save(os.path.join(userImagePath, newImageFile + '.' + ext))

    ## 展示大图 600 * 1024
    clipFile(os.path.join(userImagePath, newImageFile + '.' + ext), IMAGE_RANG, os.path.join(userImagePath, newImageFile + '_s01.' + ext))

    ## 缩略图 150 * 150
    clipFile(os.path.join(userImagePath, newImageFile + '.' + ext), THUMBNAIL_RANG1, os.path.join(userImagePath, newImageFile + '_s02.' + ext))

    ## 最小缩略图 100 * 100
    clipFile(os.path.join(userImagePath, newImageFile + '.' + ext), THUMBNAIL_RANG2, os.path.join(userImagePath, newImageFile + '_s03.' + ext))
    return success({'image' : os.path.join('images', os.path.join(uid, newImageFile + '_s01.' + ext)), 'thumb' : os.path.join('images', os.path.join(uid, newImageFile + '_s02.' + ext))})

def clipFile(orgFile, rang, saveFile, isResize=False):
    ''' 保存 '''
    im = Image.open(orgFile)
    if im.mode != 'RGBA':
        im_format = 'JPEG'
    else:
        im_format = 'PNG'
    if isResize:
        im.resize(rang, Image.BILINEAR)
    else :
        im.thumbnail(rang, Image.ANTIALIAS)
    im.save(saveFile, im_format)

AVENDAR_RANG1 = 64, 64
AVENDAR_RANG2 = 32, 32
@app.route('/upload/hf/', methods=['POST'])
def head_pic_upload():
    ''' head url = images/{uid}/{uid}_s01.jpg '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'无权限，请登录')
    userImagePath = os.path.join(getProperty('upload_folder'), uid)
    if not os.path.exists(userImagePath):
        os.mkdir(userImagePath)
    imgFile = request.files['imgFile']
    if imgFile == None or not allowed_file(imgFile.filename):
        return error('610', u'文件格式不合法')

    ## 保存原图
    ctime = datetime.now()
    newImageFile = ctime.strftime("%y%m%d_%H%M%S_") + ctime.microsecond
    imgFile.save(os.path.join(userImagePath, newImageFile + '.jpg'))

    ## 生成2张缩略图
    clipFile(os.path.join(userImagePath, newImageFile + '.jpg'), AVENDAR_RANG1, os.path.join(userImagePath, uid + '_s01.jpg'), True)
    clipFile(os.path.join(userImagePath, newImageFile + '.jpg'), AVENDAR_RANG1, os.path.join(userImagePath, uid + '_s02.jpg'), True)
    return success({'image' : os.path.join('images', os.path.join(uid, uid + '_s01.jpg'))})

if __name__ == '__main__':
    print 'start ... '
    # app.debug = False
    app.run(host='0.0.0.0', debug=True)
    # app.run(host='127.0.0.1', port=7000, debug=True)
